// content-scripts/utils/html2canvas-loader.js
class Html2CanvasLoader {
    static instance;
    static isInitializing = false;

    constructor() {
        if (Html2CanvasLoader.instance) return Html2CanvasLoader.instance;

        this.loadPromise = null;
        this.isLoaded = false;
        Html2CanvasLoader.instance = this;
    }

    async load() {
        // 已加载或正在加载
        if (this.isLoaded) return true;
        if (this.loadPromise) return this.loadPromise;

        // 检查可能的全局存在
        if (typeof window.html2canvas !== 'undefined') {
            this.isLoaded = true;
            return true;
        }

        // 开始加载
        this.loadPromise = new Promise(async (resolve, reject) => {
            // 双重检查防止竞态
            if (this.isLoaded) return resolve(true);

            // 创建脚本标签
            const script = document.createElement('script');
            script.src = chrome.runtime.getURL('content-scripts/html2canvas.min.js');
            script.async = true;
            script.defer = true;

            // 加载事件处理
            script.onload = () => {
                if (typeof window.html2canvas === 'undefined') {
                    reject(new Error('LIBRARY_NOT_AVAILABLE'));
                    return;
                }
                this.isLoaded = true;
                resolve(true);
            };

            script.onerror = (err) => {
                console.error('html2canvas 加载失败:', err);
                reject(new Error('LOAD_FAILURE'));
            };

            // 插入DOM
            const anchor = document.head || document.documentElement;
            anchor.appendChild(script);
        });

        return this.loadPromise;
    }
}

export const html2CanvasLoader = new Html2CanvasLoader();
